const canvas1 = document.createElement('canvas');
const canvas2 = document.createElement('canvas') ;
const ctx1 = canvas1.getContext('2d') ;
const ctx2 = canvas2.getContext('2d') ;

function initCanvas(canvas){
    canvas.width = 400 ;
    canvas.height = 400 ;
    document.body.append(canvas) ;
}

initCanvas(canvas1);
initCanvas(canvas2) ;


const cell = 20 ;
const grid = {} ;
function initGrid(){
    for(let i=0;i<canvas1.width/cell;i++){
        for(let j = 0;j<canvas1.height/cell;j++){
            grid[`${i*cell}-${j*cell}`] = 0 ;
        }
    }
}
initGrid();


//绘制棋盘
function drawBoard(){
    ctx1.save();
    ctx1.strokeStyle = '#ccc' ;
    for(let i=0;i<canvas1.width/cell;i++){
        ctx1.beginPath();
        ctx1.moveTo(cell*i,0) ;
        ctx1.lineTo(cell*i,canvas1.height);
        ctx1.stroke();

        ctx1.beginPath();
        ctx1.moveTo(0,cell*i);
        ctx1.lineTo(canvas1.width,cell*i);
        ctx1.stroke();

    }
    ctx1.restore() ;
}
drawBoard();


//蛇头，蛇身（每一部分），食物
class Rect{
    constructor(x,y,type,color = '#fac',){
        this.x = x ;
        this.y = y ;
        this.oldX = x ;
        this.oldY = y ;
        this.color = color ;
        this.w = cell ;
        this.h = cell ;
        this.type = type ;
    }
    draw(){
        //修改格子的状态,将之前占用的格子释放， 将新格子占用
        grid[`${this.oldX}-${this.oldY}`] = 0 ;
        grid[`${this.x}-${this.y}`] = this.type ;

        ctx2.clearRect(this.oldX,this.oldY,this.w,this.h);
        this.oldX = this.x ;
        this.oldY = this.y ;
        ctx2.save();
        ctx2.beginPath();
        ctx2.fillStyle = this.color ;
        ctx2.fillRect(this.x,this.y,this.w,this.h);
        ctx2.restore();
    }
}

//dir = ArrowRight , ArrowDown , ArrowLeft , ArrowUp
class Snake{
    constructor(x,y,dir = 'ArrowRight'){
        this.x = x * cell ;
        this.y = y * cell ;
        this.dir = dir ;
        this.head = new Rect(this.x,this.y,1,'#f00');
        this.body = [] ;
        this.score = 0 ;
    }
    draw(){
        //绘制蛇，就是绘制head 和 body矩形
        this.head.draw();

        if(this.body.length > 0){
            this.body[0].draw();
        }
    }
    move(){
        switch(this.dir){
            case 'ArrowRight' : this.head.x += cell ;break ;
            case 'ArrowDown' : this.head.y += cell ;break ;
            case 'ArrowLeft' : this.head.x -= cell ;break ;
            case 'ArrowUp' : this.head.y -= cell ;break ;
        }

        //判断是否到达临界点
        if(this.isOver()){
            alert('游戏结束，最终得分【'+this.score+'】')  ;
            return ;
        }

        if(this.isEat()){
            this.score += 10 ;
            //吃到食物，身体要增加一部分
            const rect = new Rect(this.head.oldX,this.head.oldY,1);
            this.body.unshift(rect);
            randomFood();
        }else{
            //没有吃到食物，蛇也要移动，蛇头移动，让蛇尾的那矩形，代替刚刚蛇头位置
            //也就是body中最后一个部分变成了最开始部分
            if(this.body.length > 0){
                const last = this.body.pop();
                last.x = this.head.oldX ;
                last.y = this.head.oldY ;
                this.body.unshift(last);
            }
        }

        this.draw();

        setTimeout(()=>{
            this.move();
        }, (200-this.score/2));
    }
    isOver(){
        return this.head.x < 0 
            || this.head.y < 0 
            || this.head.x >=canvas2.width 
            || this.head.y >= canvas2.height 
            || grid[`${this.head.x}-${this.head.y}`] == 1;
    }
    isEat(){
        return this.head.x == food.x && this.head.y == food.y ;
    }
}

let food ;
//随机生成食物
function  randomFood(){
    while(true){
        const x = Math.floor(Math.random() * canvas1.width / cell)  * cell;
        const y = Math.floor(Math.random() * canvas1.height / cell)  * cell;
        if(grid[`${x}-${y}`] == 0){
            //随机的位置空闲的，创建食物了
            food = new Rect(x , y , 2,'#00f');
            food.draw();
            break ;
        }
    }
}
randomFood();




//点击开始游戏
canvas2.onclick = function(){
    //清空上一次效果
    ctx2.clearRect(0,0,canvas2.width,canvas2.height);
    randomFood();
    initGrid();


    const snake = new Snake(10,10);
    snake.draw();
    snake.move();
    
    
    document.onkeydown = function(e){
        if(e.code == 'ArrowRight' || e.code == 'ArrowDown' || e.code == 'ArrowLeft' || e.code == 'ArrowUp'){
            //方向改变失效（相反方向改变）
            if(snake.dir == 'ArrowRight' && e.code == 'ArrowLeft'
                ||snake.dir == 'ArrowLeft' && e.code == 'ArrowRight'
                ||snake.dir == 'ArrowDown' && e.code == 'ArrowUp'
                ||snake.dir == 'ArrowUp' && e.code == 'ArrowDown'){
                return ;
            }
            snake.dir = e.code;
        }
    }
}

